import urllib.request
import requests
import json
import time
import os
import logging
import platform
import datetime


info = logging.getLogger(__name__).info
err = logging.getLogger(__name__).error

DEVICE_ID = 8

# HOST = 'http://127.0.0.1:8080'
HOST = 'https://www.scanprinter.online/scan-printer-1.0'
DOWNLOAD_DIR='DOWNLOAD_DIR'


class PrintTask(object):
    def __init__(self, id, copies, createTime, deviceId, fileSender, fileType, filename, printerName, state, *args, **kwargs):
        self.id = id
        self.copies = copies
        self.createTime = createTime
        self.deviceId = deviceId
        self.fileSender = fileSender
        self.fileType = fileType
        self.filename = filename
        self.printerName = printerName
        self.state = state


def queryTask():
    dev_get_task_url = HOST+'/ptask/getTask?deviceId='+str(DEVICE_ID)
    try:
        f = urllib.request.urlopen(dev_get_task_url)
        if f is not None:
            if f.code == 200:
                result = json.loads(f.read().decode('utf-8'))
                if result["code"] == 200:
                    task = result["data"]
                    if task is not None:
                        return PrintTask(**task)
    except urllib.error.URLError as e:
        # err('Network error: URL Error: %s',Err)
        err(e)

    return None


def downloadTask(printTask):
    dev_download_url = HOST+'/ptask/downloadFile?taskId='+str(printTask.id)
    info("Download started...")
    r = requests.get(dev_download_url)
    f = open(printTask.filename, 'wb')
    f.write(r.content)
    f.close()


def printTask(printTask):
    sysstr = platform.system()

    if(sysstr == "Windows"):
        info('Printing...'+printTask.filename)
        # os.system('lp -U pi ' + printTask.filename)
        info('Delete...'+printTask.filename)
        os.system('del -Q ' + printTask.filename)

    elif sysstr == "Linux":
        info('Printing...'+printTask.filename)
        os.system('lp -U pi ' + printTask.filename)
        # os.system('lp -U pi ' + printTask.filename)
        taskStr = "lp -U -n %s pi %s " %(printTask.copies, printTask.filename)
        os.system(taskStr)
        info('Delete...'+printTask.filename)
        os.system('rm ' + printTask.filename)

    else:
        info('Operation System style missed...')
        pass


def finishTask(task):
    url = HOST+'/ptask/finish'
    info("Finish...")
    requests.post(url, data={'taskId': task.id})


def main():
    logging.basicConfig(
        level=logging.INFO,
        format=("%(relativeCreated)04d %(process)05d %(threadName)-10s " "%(levelname)-5s %(msg)s"))

    info("Start working....")
    while True:
        time.sleep(5)
        task = queryTask()
        if task is not None:
            info('Get work... '+task.filename)
            downloadTask(task)
            printTask(task)
            finishTask(task)
        else:
            info('Queue empty......')


if __name__ == "__main__":
    main()
